import {ref, watch, computed} from "vue";
import {useRoute} from "vue-router";
import {useAppStore, useRouteStore} from "@/store/index.js";
import {findParent} from "@/tools/index.js";

export function useMenu() {
    const route = useRoute();
    const appStore = useAppStore();
    const routeStore = useRouteStore();
    const selectedKeys = ref([]);
    const menuStore = computed(() => routeStore.routes);
    const openKeys = ref([]);
    const lastOpenKeys = ref([]);
    const layout = computed(() => appStore.layout);
    const menus = ref(menuStore.value);

    watch(() => route.path, (path) => {
        selectedKeys.value = [path];
        let result = findParent(menus.value, path);
        if (layout.value !== 'layout-head') {
            openKeys.value = result;
            lastOpenKeys.value = result;
        }
    }, {immediate: true});

    watch(() => layout.value, (layout) => {
        if (layout === "layout-comp") {
            menus.value = routeStore.routes.find((r) => r.path === route.matched[0].path).children;
        } else {
            menus.value = routeStore.routes;
        }
    }, {immediate: true});

    function openChange(keys) {
        if (appStore.layout === "layout-head") {
            return;
        }
        const lastPath = keys.find(key => lastOpenKeys.value.indexOf(key) === -1);
        let oneLevelMenu = [];
        menus.value.filter(s => s.parent === 0).forEach(s => {
            oneLevelMenu.push(s.path);
        })
        if (!oneLevelMenu.includes(lastPath)) {
            openKeys.value = keys;
            lastOpenKeys.value = keys;
        } else {
            let normalizePath = lastPath ? [lastPath] : [];
            openKeys.value = normalizePath
            lastOpenKeys.value = normalizePath
        }
    }

    return {
        selectedKeys, openKeys, openChange, menus,
    }
}